<style>
  .amap-info-close {
    position: absolute;
    top: 5px;
    color: #c3c3c3;
    text-decoration: none;
    width: 14px;
    height: 14px;
    display: none;
  }
</style>
<template>
  <div class="amap-page-container">
    <vxe-toolbar fixed="top">
      <template v-slot:buttons>
        <el-button @click="confirm" type="primary">选中标点</el-button>
        <el-button @click="cancle" type="primary">取消标点</el-button>
      </template>
    </vxe-toolbar>
    <div style="position:relative;height:80%;">
      <div class="search-box">
        <input v-model="searchKey" type="search" id="search">
        <button @click="searchByHand">搜索</button>
        <div class="tip-box" id="searchTip"></div>
      </div>
      <el-amap
        vid="amap"
        :plugin="plugin"
        :center="center"
        :zoom="zoom"
        :events="events"
        :amap-manager="amapManager"
      >
        <el-amap-marker
          :position="marker.position"
          draggable="false"
          clickable="false"
          bubble="true"
          :events="marker.events"
        ></el-amap-marker>
        <!-- 信息窗口 -->
        <el-amap-info-window
          :position="currentWindow.position"
          :visible="currentWindow.visible"
          :events="currentWindow.events"
          :offset="currentWindow.offset"
          :class="amap-info-close"
        >
          <div :style="slotStyle" class="windowStyle">
            <b>名称：</b>
            {{name}}
            <br />
            <b>地址：</b>
            {{address}}
            <br />
            <b>经度</b>
            &nbsp;&nbsp;&nbsp;{{lng}}
            <br />
            <b>纬度</b>
            &nbsp;&nbsp;&nbsp;{{lat}}
            <!-- <br/>
            <button @click="confirm">确定</button>&nbsp;&nbsp;&nbsp;
            <button @click="cancle">取消</button> -->
          </div>
        </el-amap-info-window>
      </el-amap>
    </div>
  </div>
</template>

<script>
import Cookies from "js-cookie";

// 引入vue-amap
import VueAMap from "vue-amap";
Vue.use(VueAMap);

// 初始化vue-amap
VueAMap.initAMapApiLoader({
  // 高德的key
  key: JSON.parse(localStorage.getItem('dataBranch')).partyGroupConfigCacheMap.amapKey_webJs.configValue,
  // 插件集合
  plugin: [
    "AMap.Autocomplete",
    "AMap.PlaceSearch",
    "AMap.Scale",
    "AMap.OverView",
    "AMap.ToolBar",
    "AMap.MapType",
    "AMap.PolyEditor",
    "AMap.CircleEditor",
    "AMap.Geocoder",
    "AMap.Geolocation"
  ],
  // 高德 sdk 版本，默认为 1.4.4
  v: "1.4.4",
  uiVersion: '1.0'
})
import Vue from "vue";
import request from "@/utils/request";
import {AMapManager,lazyAMapApiLoaderInstance} from "vue-amap";
const amapManager = new AMapManager();
export default {
  name: "mapSelect",
  data() {
    let self = this;
    return {
      searchKey: '',
      zoom: 12,
      center: [118.311371,35.140127],
      address: "",
      name: "",
      lng: 121.630925,
      lat: 29.866002,
      loaded: false,
      currentLocation: '',
      plugin:[
        {
          // 定位
          pName: 'Geolocation',
          events: {
            init(o) {
               // o是高德地图定位插件实例
              o.getCurrentPosition((status, result) => {
                if (result && result.position) {
                  // 设置经度
                  self.lng = result.position.lng
                  // 设置维度
                  self.lat = result.position.lat
                  // 设置坐标
                  self.center = [self.lng, self.lat]
                  self.address = result.formattedAddress,
                  self.adcode = result.addressComponent.adcode
                  let district = result.addressComponent.district
                  let address = result.formattedAddress
                  if(result.formattedAddress.indexOf(district)>-1){
                    address = result.formattedAddress.substring(result.formattedAddress.indexOf(district)+district.length,result.formattedAddress.length)
                  }
                  self.name = address
                  self.currentLocation = {
                    center: self.center,
                    address: self.address,
                    name: self.name,
                    adcode: self.adcode,
                    lng:self.lng,
                    lat: self.lat,
                  }
                  // load
                  self.loaded = true
                  // 页面渲染好后
                  self.$nextTick()
                }
              })
            }
          }
        }
      ],
      searchOption: {
        city: "全国",
        citylimit: true
      },
      shipmentUserCode:"",
      amapManager: amapManager,
      driverName:"",
      driverCode:"",
      marker:
      {
        position: [118.311371,35.140127],
        events: {
          dragstart: e => {
            this.currentWindow.visible = false;
          },
          dragend: e => {
            this.marker.position = [e.lnglat.lng, e.lnglat.lat];
            this.currentWindow.visible = true;
            this.currentWindow.position = [e.lnglat.lng, e.lnglat.lat];
          }
        },
        visible: true
      },
      windows: [],
      window: "",
      events: {
         init() {
          lazyAMapApiLoaderInstance.load().then(() => {
            self.initSearch()
          })
        },
        click(e) {
          //添加标记点
          self.addMarker(e)
        }
      },
      currentWindow: {
        position: [118.311371,35.140127],
        offset: [0, -28],
        events: {
          close() {
          }
        },
        visible: false
      },
      slotStyle: {
        padding: "2px 8px",
        color: "#333"
      },
      loading: {},
      delivery: {},
      adcode:'',
      infoWindow:''
    };
  },
  created() {
    this.currentWindow.visible = false;
  },
  mounted() {},
  methods: {
    amap(){},
    info(){},
    close(){},
    confirm() {
      this.currentWindow.visible = false;
      this.$emit("fatherMethod", this.address, this.name, this.center,this.adcode);
      this.currentWindow.events.close();
    },
    cancle() {
      this.currentWindow.visible = false;
    },
    //搜索下拉选点击事件
    onSearchResult(pois) {
      //添加标记点
      this.addMarker({"lnglat":pois[0].location});

    },
    switchWindow() {
      const site = [this.lng, this.lat];
      this.center = site;
      this.zoom = 14;
      this.marker.position = site;
      this.currentWindow.position = site;
      this.currentWindow.visible = true;
    },
    initShow(tab) {
      this.currentWindow.visible = false
      if (tab) {
        var tabData = tab
        var siteArr = []
        siteArr = tabData.location.split(",")
        this.center = siteArr
        this.zoom = 14
        this.adcode = tab.adcode
        this.marker.position = siteArr
        this.currentWindow.position = siteArr
        this.address =
          tabData.pname + tabData.cityname + tabData.adname + tabData.address
        this.name = tab.name
        this.lng = siteArr[0]
        this.lat = siteArr[1]
         this.currentWindow.visible = true
      }else if(this.currentLocation){
        this.center = this.currentLocation.center
        this.zoom = 14
        this.adcode = this.currentLocation.adcode
        this.marker.position = this.currentLocation.center
        this.currentWindow.position = this.currentLocation.center
        this.address = this.currentLocation.address
        this.name = this.currentLocation.name
        this.lng = this.currentLocation.lng
        this.lat = this.currentLocation.lat
         this.currentWindow.visible = true
      }
     
    },
    //添加标记点
    addMarker(e){
      let self = this;
      let { lng, lat } = e.lnglat;
      self.lng = lng;
      self.lat = lat;
      // 这里通过高德 SDK 完成。
      var geocoder = new AMap.Geocoder({
        radius: 1000,
        extensions: "all",
        homeorcorp: 2
      });
      geocoder.getAddress([lng, lat], function(status, result) {
        if (status === "complete" && result.info === "OK") {
          if (result && result.regeocode) {
            self.adcode = result.regeocode.addressComponent.adcode
            self.address = result.regeocode.formattedAddress;
            self.name = result.regeocode.pois[0].name;
            self.switchWindow();
            self.$nextTick();
          }
        }
      });
      
    },
    initSearch() {
      let vm = this
      let map = this.amapManager.getMap()
      AMapUI.loadUI(['misc/PoiPicker'], function(PoiPicker) {
        var poiPicker = new PoiPicker({
          // city: '371300',
          // citylimit: true,
          input: 'search',
          placeSearchOptions: {
            map: map,
            pageSize: 10
          },
          suggestContainer: 'searchTip',
          searchResultsContainer: 'searchTip'
        })
        vm.poiPicker = poiPicker
        // 监听poi选中信息
        poiPicker.on('poiPicked', function(poiResult) {
          let source = poiResult.source
          let poi = poiResult.item
          if (source !== 'search') {
            poiPicker.searchByKeyword(poi.name)
          } else {
            poiPicker.clearSearchResults()
            let lng = poi.location.lng
            let lat = poi.location.lat
            let address = poi.pname +　poi.cityname + poi.adname + poi.address
            vm.currentWindow.visible = false
            vm.lng = lng
            vm.lat = lat
            vm.address = address
            vm.searchKey = ''
            vm.adcode = poi.adcode
            vm.name = poi.name
            vm.center = [lng,lat]
            // vm.switchWindow()
            vm.newInfoWindow()
          }
        })
      })
    },
    searchByHand() {
      if (this.searchKey !== '') {
        this.poiPicker.searchByKeyword(this.searchKey)
      }
    },
    newInfoWindow() {
      let infoWindow = new AMap.InfoWindow({
        offset: new AMap.Pixel(0, -20)
      })
      infoWindow.setMap(this.amapManager.getMap())
      infoWindow.setPosition(this.center)
      infoWindow.open(this.amapManager.getMap(), this.center)
      infoWindow.setContent(`
          <div :style="slotStyle" class="windowStyle">
          <b>名称：</b>
          ${this.name}
          <br />
          <b>地址：</b>
          ${this.address}
          <br />
          <b>经度</b>
          &nbsp;&nbsp;&nbsp;${this.lng}
          <br />
          <b>纬度</b>
          &nbsp;&nbsp;&nbsp;${this.lat}
        </div>
            `)
       this.infoWindow = infoWindow
    },
  }
};
</script>

<style scoped>
.amap-orderMana {
  height: 400px;
}
.search-box {
  position: absolute;
  top: 25px;
  left: 20px;
}

.amap-page-container {
  position: relative;
  height:100%;
}

.search-box {
  position: absolute;
  top: 10px;
  left: 10px;
}
/* .windowStyle {
  border-radius: 10px;
  padding: 10px;
  border: 1px #999 solid;
  background-color: white;
} */
.search-box {
  position: absolute;
  z-index: 5;
  width: 70%;
  left: 13%;
  top: 10px;
  height: 30px;
}

.search-box input {
  float: left;
  width: 80%;
  height: 100%;
  border: 1px solid #2882fe;
  padding: 0 8px;
  outline: none;
}

.search-box button {
  float: left;
  width: 20%;
  height: 100%;
  background: #2882fe;
  border: 1px solid #2882fe;
  color: #fff;
  outline: none;
}

.tip-box {
  width: 100%;
  max-height: 260px;
  position: absolute;
  top: 30px;
  overflow-y: auto;
  background-color: #fff;
}
</style>
